﻿using System;
using System.Web;
using Microsoft.SharePoint;
using System.Text;

namespace ExportListDatatoCSV
{
    public class ExportHandler : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            Guid gd = new Guid("");
            ExportToCSV(context, SPContext.Current.Web.Lists[gd].Items);  
        }

        private void ExportToCSV(HttpContext context, SPListItemCollection dtData)
        {
              
           context.Response.ContentType = "Application/x-msexcel";
           context.Response.AddHeader("content-disposition", "attachment;filename=" + dtData.List.Title.Replace(" ", "") + ".csv");
           context.Response.Write(GetCSV(dtData));
           context.Response.End();
        }

        private string GetCSV(SPListItemCollection dataTable)
        {
            //create the stringbuilder that would hold the data
            StringBuilder sb = new StringBuilder();
            //check if there are columns in the datatable
            if (dataTable.Count != 0)
            {
                //loop thru each of the columns for headers
                foreach (SPField column in dataTable.Fields)
                {
                    //append the column name followed by the separator
                    if (!column.Hidden)
                    {
                        sb.Append(column.Title.Replace(",", "") + ',');
                    }
                }
                //append a carriage return
                sb.Append("\r\n");

                //loop thru each row of the datatable
                foreach (SPListItem row in dataTable)
                {
                    foreach (SPField column in dataTable.Fields)
                    {
                        //append the column name followed by the separator
                        if (!column.Hidden)
                        {
                            sb.Append(Convert.ToString(row[column.InternalName]).Replace(",", "") + ',');
                        }
                    }
                    //append a carriage return
                    sb.Append("\r\n");
                }
            }
            return sb.ToString();
        }
        #endregion
    }
}
